package com.bjpowernode.rbac.service.impl;

import com.bjpowernode.rbac.anno.RequestPermission;
import com.bjpowernode.rbac.entity.Permission;
import com.bjpowernode.rbac.mapper.PermissionMapper;
import com.bjpowernode.rbac.mapper.RoleMapper;
import com.bjpowernode.rbac.query.QueryObject;
import com.bjpowernode.rbac.service.PermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author jy
 * @version 1.0
 * @date 2022/2/10 18:23
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private ApplicationContext context;

    @Override
    public PageInfo<Permission> selectPermissionByCondition(QueryObject queryObject) {
        PageHelper.startPage(queryObject.getCurrentPage(),queryObject.getPageSize());
        List<Permission> permissionList = permissionMapper.selectByCondition(queryObject);
        return new PageInfo<>(permissionList);
    }

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }


    @Override
    public void reload() {
        //清除所有角色和权限的关系
        roleMapper.deleteAllRelation();
        //把旧的权限标识删除
        permissionMapper.deleteAll();

        //把 controller中的方法上面的RequestPermission注解中的内容 获取出来，插入到数据库中
        // 目标分解：
        // 获取所有的controller
        Map<String, Object> beansWithAnnotation = context.getBeansWithAnnotation(Controller.class);
        //获取所有controller类的对象
        Collection<Object> controllers = beansWithAnnotation.values();
        //获取所有的controller中的方法
        for (Object controller : controllers) {
            Method[] declaredMethods = controller.getClass().getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                //获取所有方法上面带有自定义注解的注解对象
                if (declaredMethod.isAnnotationPresent(RequestPermission.class)){
                    //获取每一个带有@RequestPermission注解的方法的注解信息
                    RequestPermission annotation = declaredMethod.getAnnotation(RequestPermission.class);
                    //把数据对象中的数据取出，插入到数据库中
                    String[] value = annotation.value();
                    String name = value[0];
                    String expression = value[1];
                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setExpression(expression);
                    permissionMapper.insert(permission);
                }
            }
        }
    }
}
